<div class="app-content-body ">
    <div class="bg-light lter b-b wrapper-md hidden-print">
      <h1 class="m-n font-thin h3">更改代理</h1>
    </div>

    <div class="form_title">
      <div class="my_hd edit-type">编辑</div>
      <div class="crud-container crud-reset">
        <form id="form-container">
          <div class="row"> 
            <div class="col-sm-12">
              <div id="form"></div>
            </div>
          </div>          
          <div class="row">
            <div class="col-sm-12 text-right">
                <div id="cancel"></div>
                <div id="save"></div>
            </div>
          </div>
        </form>
      </div>
    </div>
</div>
<script type="text/javascript">
$(function () {  
    
    $("#content").one("route.loaded", function(e, context) {
      var memberStore = $.crudStore(API('members')), id = context.params.id || 0, formData = {};

      id = parseInt(id);

      $.crudStore(API('agent-area')).load().then(function (resp) {
        var data = resp.data;

        if (data.length > 0) {
          
          var map = {};

          for (var i = 0; i < data.length; i++) {
            if (data[i].parent_id == 0) {
              data[i].path = data[i].name;
              map[data[i].id] = data[i].path;
            }
          }

          var step = 2;

          while (--step >= 0) {
            for (var i = 0; i < data.length; i++) {
              if (! data[i].path && map[data[i].parent_id]) {
                var path = map[data[i].parent_id] + " " + data[i].name;
                data[i].path = path;
                map[data[i].id] = path;
              }
            }
          }
        }

        console.log(data);

        return data;
      }).then(function (data) {

        var agentData = null;

        if (id) {
          $.each(data, function (i, item) {
            if (item.id === id) {
              agentData = item.agent;

              return false;
            }
          })
        }

        var formData = {
          money: 0, 
          remark: agentData ? agentData.remarks : '',
          agent_area_id: id,
          user: {}
        };


        var formItems = [{
          dataField: "user.uname",
          label: {text: '会员姓名'},
          editorType: 'dxAutocomplete',
          editorOptions: {
            dataSource: memberStore,
            placeholder: "按姓名，手机号码，身份证，会员卡号搜索",
            searchExpr: ['uname', 'mobile'],
            valueExpr: "id",
            itemTemplate: function(data) {
                return data ? $("<div>" + (data.uname || "") + 
                    " - " + (data.mobile || "") + "" + "</div>") : null;
            },
            onItemClick: function(e) {
              var form = $("#form").dxForm("instance"), 
                data = $.extend({}, form.option('formData'), {
                  user: e.itemData,
                  default_user_id: e.itemData.id,
                  default_user_name: e.itemData.uname,
                  default_user_mobile: e.itemData.mobile,
                  quantity: e.itemData.subject_count,
                  agent_area_id: ''
                });

              form.updateData(data);
            }
          }
        },{
          dataField: "user.identity_card",
          label: {text: '身份证号'},
          editorOptions: {readOnly: true}
        },{
          dataField: "user.mobile",
          label: {text: '会员手机'},
          editorOptions: {readOnly: true}
        },{
          dataField: "user.member_card",
          label: {text: '会员卡号'},
          editorOptions: {readOnly: true}
        }/*,{
          dataField: "agent_level",
          label: {text: '代理类型'},
          editorType: 'dxRadioGroup',
          editorOptions: {
            items: [{key: 1, name: '省级代理'}, {key: 2, name: '市级代理'}, {key: 3, name: '区县级代理'}],
            layout: "horizontal",
            displayExpr: 'name',
            valueExpr: 'key',
            value: 1
          }
        }*/,{
          dataField: "agent_area_id",
          label: {text: '代理区域'},
          editorType: 'dxDropDownBox',
          editorOptions: {
            valueExpr: "id",
            displayExpr: "path",
            placeholder: "请选择代理区域",
            showClearButton: true,
            dataSource: data,
            contentTemplate: function(e) {
                var value = e.component.option("value"),
                    $treeView = $("<div>").dxTreeView({
                        dataSource: e.component.option("dataSource"),
                        dataStructure: "plain",
                        keyExpr: "id",
                        parentIdExpr: "parent_id",
                        selectionMode: "single",
                        displayExpr: "name",
                        selectByClick: true,
                        height: 300,
                        onContentReady: function(args) {
                            if (value) args.component.selectItem(value);
                        },
                        selectNodesRecursive: false,
                        onItemSelectionChanged: function(args){
                            var value = args.component.getSelectedNodesKeys();
                            
                            e.component.option("value", value.length > 0 ? value[0] : '');
                        }
                    });
                
                treeView = $treeView.dxTreeView("instance");
                
                return $treeView;
            }
          }
        }];

        if (context.params.action === 'add') {
          formItems.push({
              dataField: "money",
              label: {text: '实收金额'},
              editorType: "dxTextBox"
          });
        }

        formItems = formItems.concat([{
            dataField: "remark",
            label: {text: '合约备注'},
            editorType: "dxTextArea",
            editorOptions: {
                height: 140
            }
        },{
            dataField: "file",
            label: {text: '合约文件'},
            editorType: "dxFileUploader",
            editorOptions:{
              uploadMode: 'useForm',
              multiple: false,
              accept: "*",
              value: []
            }
        }]);

        var form = $("#form").dxForm({
          formData: formData,
          showColonAfterLabel: true,
          showValidationSummary: false,
          validationGroup: "crud",
          items: formItems
        }).dxForm("instance");

        if (agentData) {
          memberStore.byKey(agentData.default_user_id).then(function (resp) {
            form.updateData({user: resp});
          });
        }

        $(".edit-type").text(context.params.action === 'add' ? '新增代理合约' : '终止代理合约');

        $("#form-container").on("submit", function(e) {
          var data = form.option('formData'), s = $.crudStore(API("agent-history"));

          if (! data.user) {
            DevExpress.ui.dialog.alert('请指定合约对应的用户', '提示');
            return false;
          }

          $("#save").dxButton('option', 'disabled', true);

          var udata = {
            remark: data.remark,
            user_id: data.user.id,
            money: data.money,
            agent_area_id: data.agent_area_id,
            type: context.params.action === 'add' ? 1 : -1
          };

          s.insert(udata).done(function(values, resp) {
              if (resp.success) {
                DevExpress.ui.notify({
                  message: "已完成",
                }, "success", 1000);

                context.redirect("#/agents");
              } else {
                DevExpress.ui.notify({
                  message: resp.msg,
                }, "warning", 2000);
              }

              $("#save").dxButton('option', 'disabled', false);
          });

          return false;
        });

        $("#save").dxButton({
          text: context.params.action === 'add' ? "新增" : "终止",
          type: context.params.action === 'add' ? "success" : "danger",
          useSubmitBehavior: true,
          validationGroup: "crud"
        });

        $("#cancel").dxButton({
            text: "取消",
            type: "normal",
            onClick:function() {
              context.redirect("#/agents");
            }
        });

      });
      
    });
});
</script>